package com.andy.nature.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.andy.common.extend.setOnIMClickListener
import com.andy.common.model.Label
import com.andy.nature.BR
import com.andy.nature.R
import com.andy.nature.databinding.AdapterLabelDialogItemBinding

class DialogLabelAdapter : RecyclerView.Adapter<DialogLabelAdapter.BottomViewHolder>() {

    private var mContext: Context? = null
    private var allLabelList = mutableListOf<Label>()
    private var selectLabelList = mutableListOf<Label>()

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        mContext = recyclerView.context
    }

    fun setData(allLabelList: MutableList<Label>, selectLabelList: MutableList<Label>) {
        this.allLabelList.clear()
        if (allLabelList.isNotEmpty()) {
            this.allLabelList.addAll(allLabelList)
        }
        this.selectLabelList.clear()
        if (selectLabelList.isNotEmpty()) {
            this.selectLabelList.addAll(selectLabelList)
        }
        notifyDataSetChanged()
    }

    fun getSelectList(): MutableList<Label> {
        return selectLabelList
    }

    fun resetData() {
        selectLabelList.clear()
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return allLabelList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BottomViewHolder {
        val binding = AdapterLabelDialogItemBinding.inflate(LayoutInflater.from(mContext), parent, false)
        return BottomViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BottomViewHolder, position: Int) {
        val data = allLabelList[position]
        DataBindingUtil.bind<AdapterLabelDialogItemBinding>(holder.itemView)?.let {
            it.setVariable(BR.dialogLabel, data)
            it.executePendingBindings()
        }
        holder.binding.root.let {
            if (selectLabelList.contains(data)) {
                it.setBackgroundResource(R.drawable.dialog_shape_blue_r5)
            } else {
                it.setBackgroundResource(R.drawable.dialog_shape_stroke_e8e8e8_r5)
            }
            it.setOnIMClickListener {
                if (selectLabelList.contains(data)) {
                    selectLabelList.remove(data)
                } else {
                    selectLabelList.add(data)
                }
                notifyItemChanged(position)
            }
        }
    }

    class BottomViewHolder(val binding: AdapterLabelDialogItemBinding) : RecyclerView.ViewHolder(binding.root)
}